閉包(closure)的實作包含一個外層函式包裹一個內層函式,而宣告過後並不馬上執行這也讓閉包的使用不直覺,需要多閱讀一些程式碼與設計方法來熟悉。讀完這一章並沒有馬上能想到跟理解實際應用場景,但先更深入發掘了函式多變的使用方式。
裡面包括定義私有變數、Curry 化的使用、進階設定函式上下文(context)、部分套用函式並使用到 prototype 在下一章節會提到、改寫原本函式行為等進階應用等等。
//私有變數 faint 的使用
function Ninja() {
var faint = 0; //私有變數在這裡
this.getFeints = function(){
return feints;
}
this.feint = function(){
faint++;
}
}
var ninja = new Ninja();
ninja.feint();
//callback 與計時器
function animateIt(element) {
var elem = document.querySelector(element);
var tick = 0;
var timer = setInterval(function(){
if(tick < 100) {
elem.style.position = "relative";
elem.style.left = elem.style.top = tick + "px";
tick++;
} else {
clearInterval(timer);
}
}, 10)
}
animateIt(".header__logo");
function bind(context,name){
return function(){
return context[name].apply(context, arguments);
};
}
var button = {
clicked: false,
click: function(event){
event.preventDefault()
this.clicked = true;
console.log(this)
}
}
var elem = document.querySelector(".header__logo");
elem.addEventListener("click", bind(button, "click"), false);
Function.prototype.partial = function(){
var fn = this, args = Array.prototype.slice.call(arguments);
return function() {
var arg = 0;
for (var i = 0; i < args.length && arg < arguments.length; i++) {
if (args[i] === undefined) {
args[i] = arguments[arg++]
}
}
return fn.apply(this, args);
}
}
String.prototype.csv = String.prototype.split.partial(/,\s*/);
var results = ("Mugan, Jin, Fuu").csv();
Failure is simply the opportunity to begin again, this time more intelligently.
https://jigsawye.gitbooks.io/mostly-adequate-guide/content/ch4.html